#! /usr/bin/perl -w

package Session;

#use strict;

use Constants;
use Task;

our $VERSION = 1.00;

sub new{
	my ($class) = @_;
	my $self = {
		_connection => undef,
		_sid =>undef,
		_uid => undef,
		_stage =>undef,
		_tasks=>undef
	};
	bless $self;
	return $self;
}

sub init
{
	my ($self, $connection, $uid, @task_groups) = @_;

	$self->{_connection} = $connection;
	$self->{_uid} = $uid;
	$self->{_stage} = $SESSION_READY;

	#@parameters format: (task1, task2, task3, ... taskn)
	#order format: 1:2,3,4:5,6:7:8, : seperate tasks groups, task group must follow the order, no parallel; , seperate tasks
	#in one group, tasks in one group don't have to follow orders, they could execute parallely 

	$self->{_connection}->{AutoCommit} = 0;
	$self->{_connection}->{RaiseError} = 1;

	eval
	{
		$self->{_connection}->do("INSERT INTO sessions (uid, stage) VALUES ($self->{_uid}, $self->{_stage})");
		$self->{_sid}  = $self->{_connection}->last_insert_id(undef, undef, "sessions", "sid");

		my @group_ids = ();

		foreach my $task_group (@task_groups)
		{
			my @task_ids = ();

			foreach my $task (@$task_group)
			{
				my $task_id = $self->insert_tasks_to_db($task);
				push(@task_ids, $task_id);
			}

			push(@group_ids, join($TASK_SEPERATOR, @task_ids));
		}

		$self->{_tasks} = join($TASKSET_SEPERATOR, @group_ids);

		#update orders;

		$self->{_connection}->do("UPDATE sessions SET tasks = \'$self->{_tasks}\' WHERE sid = $self->{_sid}");
		
		$self->{_connection}->commit;
	};

      if($@)
      {
      		eval {$self->{_connection}->rollback};
      }

}

sub insert_tasks_to_db
{
	my ($self, $task_ref) = @_;

	my @task = @$task_ref;

	$self->{_connection}->do("INSERT INTO tasks (capabilities, stage, specified, command, logfile,  sid, createTime) VALUES (\'$task[0]\', $TASK_READY, 0, \'$task[1]\', \'$task[2]\', $self->{_sid}, CURRENT_TIMESTAMP)");

	return $self->{_connection}->last_insert_id(undef, undef, "tasks", "tid");
	
}

